package com.heima.wemedia.Interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.thread.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author itheima
 * @since 2022-07-15
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头上的userId字段
        String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(userId)) {
            log.warn("用户id为空");
            return false;
        }

        // 2. 将userId字段写入到 ThreadLocal
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(userId));
        UserThreadLocal.set(wmUser);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        // 清除ThreadLocal
        UserThreadLocal.remove();
    }

}
